// Created by wangliang on 2025/2/14.
import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:flutter_app_demo/pigeon/ruixue_plugin.dart';
import 'package:flutter_app_demo/utils/logger.dart';
import 'package:flutter_app_demo/utils/toast.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:mvvm_plus/mvvm_plus.dart';
import 'package:path/path.dart' as p;


class ImagePickerPageViewModel extends ViewModel {

  final ruixueApi = RuiXueApi();
  final ImagePicker _imagePicker = ImagePicker();
  get imagePicker => _imagePicker;

  String _progressText = "";
  get progressText => _progressText;

  static const EventChannel _progressChannel = EventChannel('image_picker_upload_progress');

  @override
  void initState() {
    super.initState();

    _progressChannel.receiveBroadcastStream().listen((event) {
        _progressText = "$event";
        buildView();
    }, onError: (error) {
      print('Error: $error');
    });
  }

  final List<String> _selectImageList = [];
  List<String> get selectImageList => _selectImageList;

  Future launchCustomAlbum() async {
    try {
      Map<String, Object> map = {};
      map["selectPaths"] = _selectImageList;
      ResponseData result = await ruixueApi.launchNativePhoto(map);
      Log.d("WLTest ${result.code} ");
      if (result.data != null) {
        List<dynamic> jsonList = jsonDecode(result.data!);
        _selectImageList.clear();
        for(int i=0;i<jsonList.length;i++) {
          Map<String, dynamic> json = jsonList[i];
          Log.d("WLTest path ${json['path']} , mineType: ${json['mimeType']}");
          _selectImageList.add(json['path']);
        }
      }
      buildView();
    } on PlatformException catch (e) {
      Log.d("WLTest launchCustomAlbum failed ${e.code} ${e.message}");
      _showToast('启动相册失败');
    }
  }

  Future pickImage(ImageSource source) async {
    XFile? file = await _imagePicker.pickImage(source: source);
    _selectImageList.clear();
    if (file != null) {
      _selectImageList.add(file.path);
    }
    buildView();
  }

  Future pickMultiImage() async {
    List<XFile> list = await _imagePicker.pickMultiImage();
    _selectImageList.clear();
    for (int i = 0; i < list.length; i++) {
      _selectImageList.add(list[i].path);
    }
    buildView();
  }

  Future upload() async {
    // 仅用于测试本地 oss 上传功能
    if (_selectImageList.isEmpty) {
      _showToast("请选择图片");
      return null;
    }

    String path = _selectImageList[0];
    String extension = p.extension(path);
    String platform = "";

    if (Platform.isAndroid) {
      platform = "android";
    } else if (Platform.isIOS) {
      platform = "ios";
    }
    String objectKey = "feed_log/flutter_test_$platform$extension";
    try {
      ResponseData data = await ruixueApi.ossUpload(objectKey, path);
      if (data.code == 0 && data.data != null) {
        var json = jsonDecode(data.data!);
        Log.d("WLTest upload result: $json");
        _showToast('上传成功');
      } else {
        _showToast('上传失败 code ${data.code} ${data.message}');
      }
    } on PlatformException catch (e) {
      Log.d("WLTest upload failed ${e.code} ${e.message}");
      _showToast('上传失败');
    }
  }

  _showToast(String content) {
    ToastUtil.showToast(context, content);
  }

  onClickImage(int index) {
    List<String> uris = [];
    for(int i = 0; i < _selectImageList.length; i++) {
      uris.add(Uri.encodeComponent(_selectImageList[i]));
    }
    uris.add(Uri.encodeComponent("https://gips2.baidu.com/it/u=1192674964,3939660937&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960"));
    Log.d("urls >>>   ${uris.join("|")}");
    context.push("/image/view?urls=${uris.join("|")}&index=$index");
  }

}